<!-- src/views/Knowledge/KnowledgeDetail.vue -->
<template>
  <div>
    <h1 class="text-2xl font-bold mb-4">{{ knowledgeTitle }}</h1>
    <!-- 动态加载对应的知识点组件 -->
    <component :is="knowledgeComponent"></component>

    <!-- 掌握程度选择 -->
    <div class="type-selection mt-6">
      <p class="text-lg font-semibold mb-2">掌握程度:</p>
      <el-radio-group v-model="selectedType">
        <el-radio value="danger">不了解</el-radio>
        <el-radio value="warning">一知半解</el-radio>
        <el-radio value="success">懂了</el-radio>
      </el-radio-group>

      <!-- 按钮布局 -->
      <div class="flex space-x-4 mt-4">
        <el-button type="default" @click="goBack">返回</el-button>
        <el-button type="primary" @click="saveType">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, defineAsyncComponent, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useKnowledgeStore } from '@/stores/knowledge'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter() // 引入 router 实例

// 返回上一页的方法
const goBack = () => {
  router.go(-1) // 使用 router.go(-1) 返回上一页
}

const store = useKnowledgeStore()

onMounted(() => {
  store.loadKnowledgePoints()
})

// 获取知识点 ID 和 类别
const knowledgeId = computed(() => route.params.id as string)
const knowledgeCategory = computed(() => route.params.category as string)

// 获取当前知识点
const knowledgePoint = computed(() =>
  store.knowledgePoints.find((point) => point.id === knowledgeId.value)
)

// 动态加载组件，并处理加载失败的情况
const knowledgeComponent = computed(() => {
  const componentName = knowledgePoint.value?.id
  console.log('hello 00', store.knowledgePoints)
  if (componentName) {
    return defineAsyncComponent(() =>
      import(`@/views/Knowledge/${knowledgeCategory.value}/${componentName}.vue`).catch((err) => {
        console.error(`Failed to load component: ${componentName}`, err)
        return import(`@/views/Knowledge/DefaultComponent.vue`)
      })
    )
  }
  return null
})

// 设置知识点标题
const knowledgeTitle = computed(() => knowledgePoint.value?.title || '')

// 设置掌握程度
const selectedType = computed({
  get: () => knowledgePoint.value?.type || 'danger',
  set: (value: 'danger' | 'warning' | 'success') => {
    store.setKnowledgeType(knowledgeId.value, value)
  }
})

// 设置掌握程度的方法
const setType = (newType: 'danger' | 'warning' | 'success') => {
  store.setKnowledgeType(knowledgeId.value, newType)
}

const saveType = () => {
  if (knowledgePoint.value) {
    store.setKnowledgeType(knowledgeId.value, selectedType.value)
    ElMessage({
      message: '掌握程度已保存',
      type: 'success'
    })
  }
}
</script>

<style scoped>
.type-selection {
  margin-top: 20px;
}
</style>
